/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package view;

import controller.ControllerEndereco;
import controller.ControllerPaciente;
import enun.EstadoCivil;
import enun.Perfil;
import enun.Sexo;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.JOptionPane;
import model.Endereco;
import model.Login;
import model.Paciente;
import util.MascaraUtil;
import util.MensagemUtil;

/**
 *
 * @author Celso Jr
 */
public class ViewPaciente extends javax.swing.JFrame {

    private final ControllerPaciente controllerPaciente;
    private final ControllerEndereco controllerEndereco;
    private final Paciente paciente;
    private int num = 0;
    private boolean veriicaClickTabela = false;
    private Login login;

    public ViewPaciente() {
        this(new Login());

    }

    public ViewPaciente(Login l) {
        this.paciente = new Paciente();
        this.controllerPaciente = new ControllerPaciente();
        this.controllerEndereco = new ControllerEndereco();
        this.login = l;
        initComponents();
        lblLogado.setText(login.getPerfil().getDescricao());

        carregarComboEstadoCivil();
        carregarComboSexo();
        carregarEndereco();
        habilitaCampos();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        txtNome = new javax.swing.JTextField();
        lblNome = new javax.swing.JLabel();
        lblEstadoCivil = new javax.swing.JLabel();
        lblIdade = new javax.swing.JLabel();
        lblSexo = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        btnCadastrar = new javax.swing.JToggleButton();
        btnAlterar = new javax.swing.JToggleButton();
        btnExcluir = new javax.swing.JToggleButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        tbPaciente = new javax.swing.JTable();
        comboSexo = new javax.swing.JComboBox();
        comboEstadoCivil = new javax.swing.JComboBox();
        lblEndereco = new javax.swing.JLabel();
        comboEndereco = new javax.swing.JComboBox();
        txtIdade = new javax.swing.JTextField();
        btnSair = new javax.swing.JButton();
        lblusuarioLogado = new javax.swing.JLabel();
        lblLogado = new javax.swing.JLabel();

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                formMouseClicked(evt);
            }
        });
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formWindowActivated(evt);
            }
        });

        lblNome.setText("Nome:");

        lblEstadoCivil.setText("Estado Civíl: ");

        lblIdade.setText("Idade:");
        lblIdade.setToolTipText("");

        lblSexo.setText("Sexo: ");

        jLabel6.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel6.setText("CADASTRO DE PACIENTE");

        btnCadastrar.setText("CADASTRAR");
        btnCadastrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCadastrarActionPerformed(evt);
            }
        });

        btnAlterar.setText("ALTERAR");
        btnAlterar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnAlterarMouseClicked(evt);
            }
        });
        btnAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAlterarActionPerformed(evt);
            }
        });

        btnExcluir.setText("EXCLUIR");
        btnExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExcluirActionPerformed(evt);
            }
        });

        tbPaciente.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        tbPaciente.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbPacienteMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(tbPaciente);

        lblEndereco.setText("Endereco:");

        comboEndereco.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Selecione" }));

        btnSair.setText("Sair");
        btnSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSairActionPerformed(evt);
            }
        });

        lblusuarioLogado.setText("Usuario logado:");

        lblLogado.setText("-");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(142, 142, 142)
                        .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 238, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(lblusuarioLogado)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(lblLogado, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblIdade)
                            .addComponent(lblSexo))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(btnSair))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(lblNome)
                                .addGap(30, 30, 30)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txtNome)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(txtIdade, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addGroup(layout.createSequentialGroup()
                                                .addComponent(comboSexo, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addGap(18, 18, 18)
                                                .addComponent(lblEstadoCivil)
                                                .addGap(18, 18, 18)
                                                .addComponent(comboEstadoCivil, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                        .addGap(0, 0, Short.MAX_VALUE))))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(btnCadastrar, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(btnAlterar, javax.swing.GroupLayout.PREFERRED_SIZE, 169, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(btnExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(lblEndereco, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(comboEndereco, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                        .addGap(0, 90, Short.MAX_VALUE)))
                .addGap(26, 26, 26))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(lblusuarioLogado)
                        .addComponent(lblLogado)))
                .addGap(39, 39, 39)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblNome))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtIdade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblIdade, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 19, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(comboEstadoCivil, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblEstadoCivil, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(comboSexo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblSexo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblEndereco)
                    .addComponent(comboEndereco, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCadastrar)
                    .addComponent(btnAlterar)
                    .addComponent(btnExcluir))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnSair)
                .addGap(7, 7, 7))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCadastrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCadastrarActionPerformed
        salvar();
    }//GEN-LAST:event_btnCadastrarActionPerformed

    private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
        carregarTable();
    }//GEN-LAST:event_formWindowActivated

    private void formMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseClicked
        // TODO add your handling code here:
    }//GEN-LAST:event_formMouseClicked

    private void tbPacienteMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbPacienteMouseClicked
        carregarInformacaoTable(evt);
    }//GEN-LAST:event_tbPacienteMouseClicked

    private void btnAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAlterarActionPerformed
        alterar();
    }//GEN-LAST:event_btnAlterarActionPerformed

    private void btnExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExcluirActionPerformed
        deletarPaciente();

    }//GEN-LAST:event_btnExcluirActionPerformed

    private void btnAlterarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnAlterarMouseClicked
        // TODO add your handling code here:
    }//GEN-LAST:event_btnAlterarMouseClicked

    private void btnSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSairActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnSairActionPerformed

    private void carregarComboSexo() {
        List<Sexo> listaSexo = new ArrayList<>();
        listaSexo = Arrays.asList(Sexo.values());
        comboSexo.removeAllItems();;
        comboSexo.addItem("Selecione");
        for (Sexo sexo : listaSexo) {
            comboSexo.addItem(sexo);
        }
        comboSexo.setEnabled(Perfil.SECRETARIA_ADM == login.getPerfil());
    }

    private void carregarComboEstadoCivil() {
        List<EstadoCivil> listaEstadoCivil = new ArrayList<>();
        listaEstadoCivil = Arrays.asList(EstadoCivil.values());
        comboEstadoCivil.removeAllItems();
        comboEstadoCivil.addItem("Selecione");
        for (EstadoCivil estadoCivil : listaEstadoCivil) {
            comboEstadoCivil.addItem(estadoCivil);
        }
        comboEstadoCivil.setEnabled(Perfil.SECRETARIA_ADM == login.getPerfil());
    }

    private void carregarInformacoesTela() {

        if (veriicaClickTabela) {
            paciente.setId((int) tbPaciente.getValueAt(num, 0));
        }

        MascaraUtil.limitarCampoTexto(txtNome, "Nome", 30);
        paciente.setNome(txtNome.getText());
        MascaraUtil.validaNumero(txtIdade, "idade");
        MascaraUtil.limitarCampoTexto(txtIdade, "Idade", 3);
        paciente.setIdade(Integer.parseInt(txtIdade.getText()));
        paciente.setEstadoCivil((EstadoCivil) comboEstadoCivil.getSelectedItem());
        paciente.setSexo((Sexo) comboSexo.getSelectedItem());
        paciente.setEndereco((Endereco) comboEndereco.getSelectedItem());
    }

    private boolean validarCampos() {
        boolean isValido = true;

        if (txtNome.getText().equals("")) {
            isValido = false;
            MensagemUtil.msgPadrao("Nome");
        }

        if (txtIdade.getText().equals("")) {
            isValido = false;
            MensagemUtil.msgPadrao("Idade");
        }

        if (comboEndereco.getSelectedItem().equals("Selecione")) {
            isValido = false;
            MensagemUtil.msgPadrao("Endereco");
        }

        if (comboEstadoCivil.getSelectedItem().equals("Selecione")) {
            isValido = false;
            MensagemUtil.msgPadrao("Estado Civil");
        }

        if (comboSexo.getSelectedItem().equals("Selecione")) {
            isValido = false;
            MensagemUtil.msgPadrao("Sexo");
        }
        return isValido;
    }

    private void salvar() {
        if (validarCampos()) {
            carregarInformacoesTela();
            controllerPaciente.inserir(paciente);
            JOptionPane.showMessageDialog(null, " Registro Cadastrado com sucesso !!");
            limparTela();
            carregarTable();
        }

    }

    private void alterar() {
        if (veriicaClickTabela) {
            if (validarCampos()) {
                carregarInformacoesTela();
                controllerPaciente.alterar(paciente);
                JOptionPane.showMessageDialog(null, "Registro alterado com sucesso!!!");
                veriicaClickTabela = false;
                limparTela();
                carregarTable();
            }
        } else {
            JOptionPane.showMessageDialog(null, "Selecione o Paciente na tabela para realizar a alteração !!!");
        }

    }

    private void carregarInformacaoTable(java.awt.event.MouseEvent evt) {

        num = tbPaciente.getSelectedRow();
        if (evt.getClickCount() == 2) {
            veriicaClickTabela = true;
            txtNome.setText((String) tbPaciente.getValueAt(num, 1));
            comboSexo.setSelectedItem(tbPaciente.getValueAt(num, 2));
            txtIdade.setText(String.valueOf(tbPaciente.getValueAt(num, 3)));
            comboEstadoCivil.setSelectedItem(tbPaciente.getValueAt(num, 4));
            comboEndereco.setSelectedItem(tbPaciente.getValueAt(num, 5));
        }
    }

    private void carregarTable() {
        TablePaciente tb = new TablePaciente();
        tb.fillingRows();
        tbPaciente.setModel(tb);
    }

    private void limparTela() {
        txtNome.setText("");
        txtIdade.setText("");
        comboEndereco.setSelectedItem(null);
        comboEstadoCivil.setSelectedItem(null);
        comboSexo.setSelectedItem(null);
        carregarEndereco();
        carregarComboSexo();
        carregarComboEstadoCivil();
    }

    private void deletarPaciente() {
        if (veriicaClickTabela) {
            String name = (String) tbPaciente.getValueAt(num, 1);
            int status = JOptionPane.showConfirmDialog(null, "Tem certeza que deseja deletar o Paciente: " + name + " ?", "Confirmação", JOptionPane.YES_NO_OPTION);
            if (status == 0) {
                paciente.setId(retornaID());
                controllerPaciente.deletar(paciente);
                JOptionPane.showMessageDialog(null, "Paciente excluido com sucesso.");
                veriicaClickTabela = false;
                limparTela();
            }
        } else {
            JOptionPane.showMessageDialog(null, "Selecione o Paciente na tabela para realizar a exclusão !!!");
        }

    }

    private void carregarEndereco() {
        List<Endereco> end = controllerEndereco.consultar();
        comboEndereco.removeAllItems();
        comboEndereco.addItem("Selecione");
        for (Endereco e : end) {
            comboEndereco.addItem(e);
        }

        comboEndereco.setEnabled(Perfil.SECRETARIA_ADM == login.getPerfil());
    }

    private Integer retornaID() {
        return (Integer) tbPaciente.getValueAt(tbPaciente.getSelectedRow(), 0);
    }

    private void habilitaCampos() {
        txtIdade.setEnabled(Perfil.SECRETARIA_ADM == login.getPerfil());
        txtNome.setEditable(Perfil.SECRETARIA_ADM == login.getPerfil());
        btnAlterar.setEnabled(Perfil.SECRETARIA_ADM == login.getPerfil());
        btnCadastrar.setEnabled(Perfil.SECRETARIA_ADM == login.getPerfil());
        btnExcluir.setEnabled(Perfil.SECRETARIA_ADM == login.getPerfil());
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JToggleButton btnAlterar;
    private javax.swing.JToggleButton btnCadastrar;
    private javax.swing.JToggleButton btnExcluir;
    private javax.swing.JButton btnSair;
    private javax.swing.JComboBox comboEndereco;
    private javax.swing.JComboBox comboEstadoCivil;
    private javax.swing.JComboBox comboSexo;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JLabel lblEndereco;
    private javax.swing.JLabel lblEstadoCivil;
    private javax.swing.JLabel lblIdade;
    private javax.swing.JLabel lblLogado;
    private javax.swing.JLabel lblNome;
    private javax.swing.JLabel lblSexo;
    private javax.swing.JLabel lblusuarioLogado;
    private javax.swing.JTable tbPaciente;
    private javax.swing.JTextField txtIdade;
    private javax.swing.JTextField txtNome;
    // End of variables declaration//GEN-END:variables
}
